//
//  UIViewControllerExt.swift
//  test-ios
//
//  Created by wyz5204 on 2023/6/6.
//

import Foundation
import UIKit

extension UIViewController {
    
    static func getCurrentViewController() -> UIViewController? {
        let keyWindow = UIApplication.shared.keyWindow
        
        guard var rootVC =  keyWindow?.rootViewController else {
            return nil ;
        }
        
        while(rootVC.presentedViewController != nil){
            rootVC = rootVC.presentedViewController!;
            if(rootVC.isKind(of: UITabBarController.self)){
                let tabVC = (rootVC as! UITabBarController)
                guard let vc = tabVC.selectedViewController else {
                    break ;
                }
                rootVC = vc;
            }else if (rootVC.isKind(of: UINavigationController.self)){
                let ngVC = (rootVC as! UINavigationController)
                guard let vc = ngVC.visibleViewController else {
                    break ;
                }
                rootVC = vc;
            }
        }
        
        if(rootVC.isKind(of: UITabBarController.self)){
            let tabVC = (rootVC as! UITabBarController)
            if let vc = tabVC.selectedViewController {
                rootVC = vc;
            }
        }else if (rootVC.isKind(of: UINavigationController.self)){
            let ngVC = (rootVC as! UINavigationController)
            if let vc = ngVC.visibleViewController  {
                rootVC = vc;
            }
        }
        
        return rootVC;
    }
    
    func startViewController(_ viewController : UIViewController , animated : Bool = true){
        self.navigationController?.pushViewController(viewController, animated: animated)
    }
    
}
